const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

// 测试图片上传API
async function testImageUpload() {
  console.log('=== 开始测试图片上传API ===');
  
  try {
    // 创建一个测试图片文件（如果不存在）
    const testImagePath = path.join(__dirname, 'test-image.jpg');
    
    // 如果没有测试图片，创建一个简单的测试文件
    if (!fs.existsSync(testImagePath)) {
      console.log('创建测试图片文件...');
      // 创建一个简单的测试图片（1x1像素的JPEG）
      const testImageBuffer = Buffer.from([
        0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01,
        0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43,
        0x00, 0x08, 0x06, 0x06, 0x07, 0x06, 0x05, 0x08, 0x07, 0x07, 0x07, 0x09,
        0x09, 0x08, 0x0A, 0x0C, 0x14, 0x0D, 0x0C, 0x0B, 0x0B, 0x0C, 0x19, 0x12,
        0x13, 0x0F, 0x14, 0x1D, 0x1A, 0x1F, 0x1E, 0x1D, 0x1A, 0x1C, 0x1C, 0x20,
        0x24, 0x2E, 0x27, 0x20, 0x22, 0x2C, 0x23, 0x1C, 0x1C, 0x28, 0x37, 0x29,
        0x2C, 0x30, 0x31, 0x34, 0x34, 0x34, 0x1F, 0x27, 0x39, 0x3D, 0x38, 0x32,
        0x3C, 0x2E, 0x33, 0x34, 0x32, 0xFF, 0xC0, 0x00, 0x0B, 0x08, 0x00, 0x01,
        0x00, 0x01, 0x01, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
        0xFF, 0xC4, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xFF, 0xC4,
        0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xDA, 0x00, 0x0C,
        0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3F, 0x00, 0x8A, 0x00,
        0x07, 0xFF, 0xD9
      ]);
      fs.writeFileSync(testImagePath, testImageBuffer);
      console.log('测试图片文件已创建:', testImagePath);
    }

    // 创建FormData
    const formData = new FormData();
    const fileStream = fs.createReadStream(testImagePath);
    formData.append('file', fileStream, 'test-image.jpg');

    console.log('📁 文件信息:');
    console.log('  文件名: test-image.jpg');
    console.log('  文件大小:', fs.statSync(testImagePath).size, 'bytes');
    console.log('  文件类型: image/jpeg');

    // 发送请求
    console.log('📤 发送请求到: /api/ImageUpload/UploadImage');
    
    const response = await axios.post('http://localhost:5000/api/ImageUpload/UploadImage', formData, {
      headers: {
        ...formData.getHeaders(),
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000,
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          console.log(`📊 上传进度: ${percentCompleted}%`);
        }
      }
    });

    console.log('=== 📥 图片上传响应 ===');
    console.log('✅ HTTP状态码:', response.status);
    console.log('📋 响应数据:', response.data);

    // 分析响应
    if (response.status >= 200 && response.status < 300) {
      console.log('✅ HTTP请求成功');
      
      if (response.data) {
        console.log('📊 API内部状态码:', response.data.code);
        console.log('💬 API消息:', response.data.message);
        
        if (response.data.code === 200 || response.data.code === 400) {
          console.log('✅ API返回成功状态码');
          
          const imageUrl = response.data.data?.url;
          if (imageUrl) {
            console.log('🎉 图片上传成功！');
            console.log('🔗 图片URL:', imageUrl);
            return imageUrl;
          } else {
            console.error('❌ 响应data中未找到url字段');
            console.error('📦 data对象:', response.data.data);
            return null;
          }
        } else {
          console.error('❌ API返回错误状态码');
          console.error('💬 错误消息:', response.data.message);
          return null;
        }
      } else {
        console.error('❌ 响应数据为空');
        return null;
      }
    } else {
      console.error('❌ HTTP请求失败');
      console.error('📊 HTTP状态码:', response.status);
      return null;
    }

  } catch (error) {
    console.error('=== 🚨 图片上传异常 ===');
    console.error('🔍 错误类型:', error.name);
    console.error('💬 错误消息:', error.message);
    
    if (error.response) {
      console.error('🌐 HTTP响应错误:');
      console.error('📊 状态码:', error.response.status);
      console.error('📋 响应数据:', error.response.data);
    }
    
    return null;
  }
}

// 运行测试
testImageUpload().then(result => {
  if (result) {
    console.log('✅ 测试成功，图片URL:', result);
  } else {
    console.log('❌ 测试失败');
  }
}).catch(error => {
  console.error('测试执行失败:', error);
}); 